// import {normalize, schema} from 'normalizr'
// import { createSelector } from "reselect";
import memoize from "lodash.memoize";
import { createSelector } from "reselect";
import { isNil } from "lodash";
/* const pageButtonSchema = new schema.Entity('pagebutton', {}, {
    idAttribute:"func_id",
    processStrategy: (value, parent, key) => ({
        ...value,
        parent: parent.id
    })
});
const submenuSchema = new schema.Entity('submenu', {children: [pageButtonSchema]}, {
    processStrategy: (value, parent, key) => ({
        ...value,
        parent: parent.id
    })
});
const menuSchema = new schema.Entity('menu', {children: [submenuSchema]}); */

const getParentPattern = pattern => {
  return pattern.replace(/(.+)\..+$/, "$1");
};
const getParent = (pattern, menus, loop = 5) => {
  if (loop > 0) {
    const target = menus.find(r => r.pattern === pattern);
    if (isNil(target)) {
      return getParent(getParentPattern(pattern), menus, loop - 1);
    } else {
      return target.pattern;
    }
  } else {
    return "";
  }
};
// const getDictionary = state => state.dictionary;
const getMenus = state => state.menus;
const getMenuSelection = state => state.menuSelection;
const getRouterParam = state => state.routerParam;

const selectors = {} as any;

/** 取得所有平台信息 */
selectors.getMenuSelection = createSelector(
  getMenuSelection,
  getMenus,
  getParent
);

/** 将menu中注入path信息 */
selectors.getPathMenu = createSelector(getMenus, menus =>
  memoize(path => {
    const pathMenus = menus.map(r => ({
      path: `${path}/${r.pattern.replace(".", "/")}`,
      ...r
    }));
    const dom = pathMenus.filter(r => r.level === "002");
    const submenu = pathMenus.filter(r => r.level === "001");
    const menu = pathMenus.filter(r => r.level === "000");
    return menu.map(r =>
      Object.assign(
        {
          children: submenu
            .filter(s => s.parentId === r.id)
            .map(t =>
              Object.assign(
                { children: dom.filter(v => v.parentId === t.id) },
                t
              )
            )
        },
        r
      )
    );
  })
);
/** 取得组件参数 */
selectors.getComponentParam = createSelector(getRouterParam, param =>
  memoize(pattern => param[pattern])
);

/** 子页面pattern时，返回母页面 */
/*selectors.getMenuSelection = createSelector(getMenus, menus =>
    memoize(pattern =>
        {
            const target = menus.find(r=>r.pattern === pattern);
            return isNil(target)
        }
    )
);*/

export default selectors;
